package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.LogicException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Override
    public void save(UserInfo userInfo) {
        userInfoRepository.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoRepository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        userInfoRepository.deleteById(id);
    }

    @Override
    public UserInfo get(String id) {
        if (StringUtils.hasLength(id)){
            Optional<UserInfo> userInfo = userInfoRepository.findById(id);
            return userInfo.orElse(null);
        }
        return null;
    }

    @Override
    public List<UserInfo> list() {
        List<UserInfo> all = userInfoRepository.findAll();
        return all;
    }

    @Override
    public boolean checkPhone(String phone) {
        UserInfo userInfo = userInfoRepository.findByPhone(phone);
        if (userInfo != null){
            throw new LogicException("该用户已注册");
        }
        return userInfo != null;
    }

    @Override
    public boolean nicknameExist(String nickname) {
        UserInfo userInfo = userInfoRepository.findByNickname(nickname);
        return userInfo!=null;
    }

    @Override
    public UserInfo login(String username, String password) {

        UserInfo user = userInfoRepository.findByPhone(username);
        if (user==null || !user.getPassword().equals(password)){
            throw new LogicException("账号或密码不正确");
        }
        return user;
    }

}
